import * as http from 'src/app/http'
import XSDK from 'src/app/lib/xsdk'

// var XLINKAPPID = '2e0fa2afc16a5000'// 正式服务器appid
var XLINKAPPID = '2e07d2af2ea4ae00' // 测试服务器appid
// var APIROOT = 'http://wx.xlink.cn' // 正式服务器RESTful接口域名
var APIROOT = 'http://139.196.164.250:8081' // 测试服务器RESTful接口域名
var userId = ''
var openId = ''

// device = {
//   userid: '',
//   deviceid: '',
//   token: ''
// }
//
// devices 为以上device数据结构数组
var devices = []

function getSearchCode () { // 获取 url上的code参数
  var search = window.location.search
  var searchs = {}
  var strs = []
  if (search.indexOf('?') !== -1) {
    search = search.substr(1)
    strs = search.split('&')
    for (var i = 0; i < strs.length; i++) {
      searchs[strs[i].split('=')[0]] = decodeURIComponent(strs[i].split('=')[1])
    }
  }

  return searchs['code']
}

function getOpenId (code) {
  return http.get(`${APIROOT}/v2/wechat_gateway/${XLINKAPPID}/get_open_id?code=${code}`)
}

function getDevices () {
  return http.get(`${APIROOT}/v2/wechat_gateway/${XLINKAPPID}/wx_device_list?access_token=XLINKUserAccessToken&open_id=${openId}`)
}

function initXSDK () {
  var ws = new XSDK('websocket', {
    type: 'remote',
    // host: 'http://cm.xlink.cn:23777',
    // host: 'http://114.55.119.222:23777',
    host: 'http://42.121.122.23:23775',
    userid: userId
  })

  ws.on('ready', () => {
    ws.emit('adddevices', devices)
  }).on('devicesready', (devices) => {
    if (!devices || devices.length <= 0) {
      return
    }
    devices.forEach(function (device) {
      device.emit('connect')
      device.on('connect', function (data) { // connect事件触发表示当前设备实例连接上了云智易服务器。
        console.log(data)
        device.on('data', function (data) {
          console.log(data)
        })
      })
      .on('statuschange', function (data) { // 0表示离线 1表示在线
        console.log(data)
        device.online = data
      })
      .on('disconnect', function (data) {
        console.log(data)
      })
    })

    window.devices = devices
    if (window.devicesReady) {
      window.devicesReady(devices)
    }
  })
}

function init () {
  var code = getSearchCode()
  getOpenId(code).then((res) => {
    if (res.status === 200) {
      var data = toObject(res.data)
      userId = data.user_id
      openId = data.open_id
      getDevices().then((res) => {
        if (res.status === 200) {
          var data = toObject(res.data)
          if (data.devices && data.devices.length > 0) {
            data.devices.forEach((item) => {
              var device = {
                userid: userId,
                deviceid: item.device_id,
                token: userId
              }

              devices.push(device)
            })
            initXSDK()
          } else {
            if (window.devicesReady) {
              window.devicesReady()
            }
          }
        }
      }).catch((err) => {
        console.log(err)
        if (window.devicesReady) {
          window.devicesReady()
        }
      })
    }
  }).catch((err) => {
    console.log(err)
    if (window.devicesReady) {
      window.devicesReady()
    }
  })
}

function toObject (str) {
  var data = {}
  if (typeof str === 'string') {
    data = JSON.parse(str)
  } else {
    data = str
  }

  return data
}

export function getDeviceInfo (deviceId) {
  return http.get(`${APIROOT}/v2/wechat_gateway/${XLINKAPPID}/device_info?open_id=${openId}&device_id=${deviceId}`)
}

export function setDeviceInfo (deviceId, params) {
  return http.post(`${APIROOT}/v2/wechat_gateway/${XLINKAPPID}/device_info?open_id=${openId}&device_id=${deviceId}`, params)
}

export default init
